package utils;

import com.intellij.ui.JBColor;
import javafx.scene.paint.Color;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;

public abstract class SRefreshHandler {
    private ArrayList<SBean> data = new ArrayList<>();
    private JTable table;
    private int[] sizes = new int[]{0, 0, 0, 0, 0};

    public SRefreshHandler(JTable table) {
        this.table = table;
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    }

    /**
     * 从网络更新数据
     *
     * @param code
     */
    public abstract void handle(List<String> code);

    /**
     * 更新全部数据
     */
    public void updateUI() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                recordTableSize();
                String[] columnNames = {"Stock Name ", "Cur Value", "Trend", "Trend Percentage", "Update Time"};
                DefaultTableModel model = new DefaultTableModel(convertData(), columnNames);
                table.setModel(model);
                updateColors();
                resizeTable();

            }
        });
    }

    private void recordTableSize() {
        FRefreshHandler.setSizeOrNot(table, sizes);
    }

    private void resizeTable() {
        for (int i = 0; i < sizes.length; i++) {
            if (sizes[i] > 0) {
                table.getColumnModel().getColumn(i).setWidth(sizes[i]);
                table.getColumnModel().getColumn(i).setPreferredWidth(sizes[i]);
            }
        }
    }

    private void updateColors() {
        table.getColumn("Trend Percentage").setCellRenderer(ColorUtils.getDefaultRenderer());
    }

    protected void updateData(SBean bean) {
        int index = data.indexOf(bean);
        if (index >= 0) {
            data.set(index, bean);
        } else {
            data.add(bean);
        }
    }

    private Object[][] convertData() {
        Object[][] temp = new Object[data.size()][5];
        for (int i = 0; i < data.size(); i++) {
            SBean fundBean = data.get(i);
            String timeStr = fundBean.getTime().substring(8);
            String changeStr = "--";
            String changePercentStr = "--";
            if (fundBean.getChange() != null) {
                changeStr = fundBean.getChange().startsWith("-") ? fundBean.getChange() : "+" + fundBean.getChange();
            }
            if (fundBean.getChangePercent() != null) {
                changePercentStr = fundBean.getChangePercent().startsWith("-") ? fundBean.getChangePercent().substring(1) : "+" + fundBean.getChangePercent();
            }
            temp[i] = new Object[]{fundBean.getName() + " (" + fundBean.getCode() + ")", fundBean.getNow(), changeStr, changePercentStr + "%", timeStr};
        }
        return temp;
    }

    protected void clear() {
        data.clear();
    }
}
